<template>
  <div class="page-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          :inline="true"
          label-position="left"
          @submit.prevent
        >
          <el-form-item :label="$t('menu.name')">
            <el-input v-model="queryParams.menuName" :placeholder="$t('dept.nameTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('status')">
            <el-select v-model="queryParams.visible" :placeholder="$t('select')" clearable @keyup.enter.native="handleQuery" style="width: 140px;">
              <el-option :label="$t('enabled')" value="1" />
              <el-option :label="$t('disabled')" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{$t('query')}}</el-button>
            <el-button @click="reset">{{$t('reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div class="tool-controls">
      <el-button type="primary" plain :icon="Plus" @click="handleAdd" :disabled="true">{{$t('add')}}</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="lists"
      :border="true"
      row-key="deptId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column :label="$t('menu.name')" prop="menuName" />
      <el-table-column :label="$t('menu.enName')" prop="menuEnName" />
      <el-table-column :label="$t('menu.icon')" align="center" prop="icon" width="120">
        <template #default="scope">
          <svg-icon :name="scope.row.icon"></svg-icon>
        </template>
      </el-table-column>
      <el-table-column :label="$t('sort')" align="center" prop="orderNum" width="100" />
      <el-table-column :label="$t('menu.visible')" align="center" prop="visible" width="100">
        <template #default="scope">
          <el-text v-if="scope.row.visible == '1'" type="success">{{$t('enabled')}}</el-text>
          <el-text v-else type="danger">{{$t('disabled')}}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="180" :formatter="formatterTime" />
      <el-table-column :label="$t('handle')" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)" :disabled="true">{{$t('edit')}}</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)" :disabled="true">{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="lists.length > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="lists.length"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>

  <!--新增修改-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="460px">
    <el-form ref="userForm" :model="menuInfo" :rules="rules" label-width="auto">
      <el-form-item :label="$t('menu.parentDept')" prop="parentId">
        <el-tree-select
          v-model="menuInfo.parentId"
          :data="treeData"
          :render-after-expand="false"
          :check-strictly="true"
          :props="{ value: 'menuId', label: 'menuName'}"
          value-key="menuId"
          node-key="menuId"
        />
      </el-form-item>
      <el-form-item :label="$t('menu.name')" prop="menuName">
        <el-input v-model="menuInfo.menuName" :placeholder="$t('menu.nameTip')" />
      </el-form-item>
      <el-form-item :label="$t('menu.enName')" prop="menuEnName">
        <el-input v-model="menuInfo.menuEnName" :placeholder="$t('menu.enNameTip')" />
      </el-form-item>
      <el-form-item :label="$t('menu.url')" prop="url">
        <el-input v-model="menuInfo.url" :placeholder="$t('menu.urlTip')" />
      </el-form-item>
      <el-form-item :label="$t('menu.icon')" prop="icon">
        <el-popover placement="bottom-start" :width="400" trigger="click" ref="popoverRef">
          <template #reference>
            <el-input v-model="menuInfo.icon" :placeholder="$t('menu.iconTip')" clearable>
              <template #prefix>
                <svg-icon :name="menuInfo.icon"></svg-icon>
              </template>
            </el-input>
          </template>
          <div class="icons-box">
            <div class="search">
              <el-input v-model="svgSearch" :placeholder="$t('menu.iconTip2')" clearable />
            </div>
            <div class="lists">
              <el-row :gutter="15">
                <el-col
                  :span="8"
                  :xs="24"
                  v-for="item in svgListComputed"
                  :key="item"
                  @click="selectIcon(item)"
                >
                  <svg-icon :name="item"></svg-icon>
                  <span class="name">{{ item }}</span>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item :label="$t('sort')" prop="orderNum">
        <el-input-number v-model="menuInfo.orderNum" :min="0" />
      </el-form-item>
      <el-form-item :label="$t('menu.outLink')" prop="target">
        <el-radio-group v-model="menuInfo.target">
          <el-radio label="1">{{$t('yes')}}</el-radio>
          <el-radio label="0">{{$t('no')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('status')" prop="visible">
        <el-radio-group v-model="menuInfo.visible">
          <el-radio label="1">{{$t('enabled')}}</el-radio>
          <el-radio label="0">{{$t('disabled')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('post.description')" prop="description">
        <el-input type="textarea" v-model="menuInfo.remark" :placeholder="$t('post.descriptionTip')" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t('confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from '#imports';
import { useI18n } from '#imports';
import type { FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const { t } = useI18n();

definePageMeta({
  title: '菜单管理',
  en_title: 'Menu Management',
})

const svgFiles = import.meta.glob("~/assets/icons/svg/*.svg", {
  eager: true,
});
const svgList = Object.keys(svgFiles).map((path) => {
  const filename: any = path.split('/').pop();
  return filename.split('.').slice(0, -1).join('.');
})
const svgSearch = ref('');
const popoverRef = ref();
const selectIcon = (icon: string) => {
  menuInfo.value = {
    ...menuInfo.value,
    icon,
  }
  popoverRef.value.hide();
}
const svgListComputed = computed(() => {
  return svgList.filter((item) => {
    return item.indexOf(svgSearch.value) !== -1;
  })
})

interface QueryParams {
  menuName: string;
  visible: string;
}

interface MenuModel {
  menuId?: string;
  menuName: string;
  menuEnName: string;
  parentId: number | string;
  orderNum: number;
  visible: string;
  target?: string;
  icon?: string;
  url?: string;
  menuType?: string;
  remark?: string;
}

const queryParams: Ref<QueryParams> = ref({
  menuName: '',
  visible: '',
})

const handleQuery = () => {
  currentPage.value = 1;
  getLists();
}

const reset = () => {
  queryParams.value = {
    menuName: '',
    visible: '',
  }
}

const dialogVisible = ref(false);
const menuInfo: Ref<MenuModel> = ref({
  parentId: '',
  menuName: '',
  menuEnName: '',
  visible: '1',
  orderNum: 0,
  target: '1',
  icon: '',
  url: '',
  menuType: '1',
  remark: '',
});
const rules = reactive<FormRules>({
  parentId: [{ required: true, message: t('menu.pearentDeptTip'), trigger: 'blur' }],
  menuName: [{ required: true, message: t('menu.nameTip'), trigger: 'blur' }],
  menuEnName: [{ required: true, message: t('menu.enNameTip'), trigger: 'blur' }],
  url: [{ required: true, message: t('menu.urlTip'), trigger: 'blur' }],
  target: [{ required: true, message: t('select'), trigger: 'change' }],
  visible: [{ required: true, message: t('select'), trigger: 'change' }],
})
const dialogTitle = ref('');
const operateType = ref('');
const handleAdd = () => {
  dialogVisible.value = true;
  operateType.value = 'add';
  dialogTitle.value = t('add');
  menuInfo.value = {
    parentId: '',
    menuName: '',
    menuEnName: '',
    visible: '1',
    orderNum: 0,
    target: '1',
    icon: '',
    url: '',
    menuType: '1',
    remark: '',
  }
}

const handleEdit = (row: MenuModel) => {
  dialogVisible.value = true;
  operateType.value = 'edit';
  dialogTitle.value = t('edit');
  menuInfo.value = row;
}

const submitForm = async () => {
  if (operateType.value === 'add') {
    const result: any = await menuCreate(menuInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('addSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  } else if (operateType.value === 'edit') {
    const result: any = await menuUpdate(menuInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('updateSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  }
}

const handleDelete = (row: MenuModel) => {
  ElMessageBox.confirm(t('confirmDelete'), t('prompt'), {
    confirmButtonText: t('confirm'),
    cancelButtonText: t('cancel'),
    type: 'warning',
  }).then(async () => {
    const result: any = await menuDelete({ menuId: row.menuId });
    if (result?.code === 200) {
      ElMessage.success(t('deleteSuccess'));
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  })
}

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const lists: Ref = ref([]);
const getLists = async () => {
  loading.value = true;
  const params: {
    page: number;
    pageSize: number;
    menuName?: string;
    visible?: string;
  } = {
    page: currentPage.value,
    pageSize: pageSize.value,
  }
  
  const { menuName, visible } = queryParams.value;
  menuName && (params.menuName = menuName);
  visible && (params.visible = visible);

  const result: any = await queryMenus(params);
  if (result?.code === 200) {
    lists.value = toTree(result.data, 'menuId', 'parentId');
  }
  loading.value = false;
}
getLists();

const treeData: Ref = ref([]);
const getTreeData = async () => {
  const result: any = await queryAllMenus();
  if (result?.code === 200) {
    treeData.value = toTree(result.data, 'menuId', 'parentId');
  }
}
getTreeData();

const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  getLists();
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getLists();
}

const formatterTime = (data : any) => {
  return formatDate(data.createTime, 'YYYY-MM-DD HH:mm:ss');
}
</script>

<style lang="less" scoped>
.icons-box {
  .lists {
    margin-top: 20px;
    height: 200px;
    overflow-y: auto;
    padding-right: 10px;
    ::v-deep(.el-col) {
      display: inline-flex;
      margin-bottom: 10px;
      align-items: center;
      cursor: pointer;
      .svg-icon {
        margin-right: 4px;
      }
    }
  }
}
</style>